
import java.net.*;
import java.io.*;

public class TCPTalker implements Runnable {

	private int port;
	private InetAddress host;
	private int packets;
	private String contents;
	private Socket s;
	private PrintWriter out;
	public boolean finished = false;
	
	public TCPTalker(int port, String host, int packets, String contents){
		try {
			this.host = InetAddress.getByName(host);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		this.port = port;
		this.packets = packets;
		this.contents = contents;
	}
	
	@Override
	public void run() {
	
		s = null;
		out = null;

		try {
			//create a socket
			s = new Socket(host, port);
			
			if(s.isClosed() || ! s.isConnected()){
				System.out.println("Talker closed");
			}
						
			//bind an outputstream to the socket
			out = new PrintWriter(s.getOutputStream());
			
			for (int i = 0; i < packets; i++) {
				
				//customise string
				String data =  contents + String.valueOf(i)+"\n";
				//System.out.println(i + " " + data);
								
				out.print(data);
				out.flush();
			}	
			
			s.close();
			s = null;
			out.close();
			return;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isFinished(){
		return true;
	}
	
}
